<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="com.google.appengine.api.datastore.Key" %>
<%@ page import="com.honkentuber.*" %>
<%@ page import="com.honkentuber.chat.*" %>
<%@ page import="java.util.List" %>
<%
  // TODO(ptucker) do not serve JSP publicly
  Room room = (Room) request.getAttribute("room");
%>
<html><head>
<title><%=room.getName()%></title>
</head><body>
<%
  Key userKey = (Key) request.getAttribute("userKey");
  MyUserCache userCache = (MyUserCache) request.getAttribute("userCache");
  MyUser user = userCache.getUsers().get(userKey);
  if (user != null) {
%>
  <p>Hello, <%=user.getNickName()%>, welcome to <b><%=room.getName()%></b>!
  (You can <a href="<%= request.getAttribute("logoutUrl") %>">sign out</a>.)</p>
<%
  } else {
%>
  <p>Hello, welcome to <b><%=room.getName()%></b>!
  <a href="<%= request.getAttribute("loginUrl") %>">Sign in</a> to include your
  name with greetings you post.</p>
<%
  }
%>
  <p>Present:
<%
  for (Presence presence : room.getPresences()) {
    Key presenceUserKey = presence.getUserKey();
    MyUser presenceUser = userCache.getUsers().get(presenceUserKey);
    String presenceUserString = (presenceUser == null)
        ? presenceUserKey.toString() : presenceUser.getNickName();
%>
<%= " " + presenceUserString %>
<%
  }
%>
  </p>
<%
  List<Message> msgs = (List<Message>) request.getAttribute("msgs");
  if (msgs.isEmpty()) {
%>
  <p>No chat history.</p>
<%
  } else {
    for (int i = msgs.size() - 1; i >= 0; --i) {
      Message msg = msgs.get(i);
      Key authorKey = msg.getAuthorKey();
      boolean isThisUser = user != null
          && user.getKey().equals(authorKey);
      if (isThisUser) {
%>
  <font size=2><b>You wrote: </b></font>
<%
      } else if (authorKey == null) {
%>
  <font size=2>An anonymous person wrote: </font>
<%
      } else {
        MyUser author = userCache.getUsers().get(authorKey);
        String authorString = (author == null)
            ? authorKey.toString() : author.getNickName();
%>
  <font size=2><%= authorString %> wrote: </font>
<%
      }
%>
  &laquo; <%= msg.getContent() %> &raquo;
  <font size=2>at <%= msg.getTimeMillis() %></font><br>
<%
    }
  }
  String roomKey = KeyFactory.keyToString(room.getKey());
%>
  <form method="post" action="/chat?html=1&form=1&roomKey=<%= roomKey %>">
    <div><input name="msg" size="64"></div>
    <div><input type="submit" value="Send" /></div>
  </form>
  <p><a href="/roomlist?html=1">Choose another room</a>.</p>
</body></html>